package com.lzm.back.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lzm.back.entity.Role;
import com.lzm.back.entity.User;
import com.lzm.back.exception.CustomeException;
import com.lzm.back.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j  // <-- 添加该注解
public class UserService {

    @Resource
    private UserMapper userMapper;

    // 定义常量提升可维护性
    private static final String CONFLICT_MSG = "该账号已存在";
    private static final String DB_ERROR_MSG = "数据库操作失败";

    public void addUser(User newUser) {
        try {
            userMapper.insertuser(newUser);
        } catch (DuplicateKeyException e) {
            // 解析数据库唯一约束异常
            String errorMsg = e.getMessage();
            if (errorMsg.contains("phone_unique")) {
                throw new CustomeException("409", "手机号已存在");
            } else if (errorMsg.contains("username_unique")) {
                throw new CustomeException("409", "用户名已存在");
            } else {
                throw new CustomeException("409", "数据冲突");
            }
        } catch (DataAccessException e) {
            log.error("数据库操作异常: {}", e.getMessage());
            throw new CustomeException("500", "数据库操作失败");
        }
        log.info("新增用户: {}", newUser);
    }


    public void updateUser(User newUser) {
        userMapper.updateUserById(newUser);
        System.out.println(newUser);
    }

    //单个删除
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);

    }

    //批量删除
    public void deleteUserByIdBatch(List<Integer> ids) {
        for (Integer id : ids) {
            userMapper.deleteUserById(id);
        }
    }

    public List<User> selectAll(User User, String role) {

        return userMapper.selectAll(User, User.getUsername(), role);
    }

    public User selectByID(Integer id) {
        return userMapper.selectByID(id);
    }

    /**
     * 分页查询
     */
    public PageInfo<User> selectPage(User User, String username, Integer pageNum, Integer pageSize, String role) {
        PageHelper.startPage(pageNum, pageSize);
        List<com.lzm.back.entity.User> userList = userMapper.selectByCondition(username, role);
        //List<user> userList = userMapper.selectAll(User, username, role);
        System.out.println("pageNum=" + pageNum + "---" + "pageSize=" + pageSize); // 打印日志

        return PageInfo.of(userList);
    }


    //登录
    public User login(User User) {
        String username = User.getUsername();
        com.lzm.back.entity.User dbUser = userMapper.getName(username);//数据库返回的用户信息
        // userService.login()中添加调试日志
        System.out.println("数据库用户角色:" + dbUser.getRole());
        System.out.println("前端提交角色:" + User.getRole());
        if (dbUser == null) {
            throw new CustomeException("500", "没有该用户");
        }

        String password = User.getPassword();
        if (!dbUser.getPassword().equals(User.getPassword())) {
            throw new CustomeException("500", "用户名或密码错误");
        }

        Role role = User.getRole();
        if (!dbUser.getRole().equals(User.getRole())) {
            throw new CustomeException("500", "用户角色不匹配");
        }

        return dbUser;
    }

    @Transactional(rollbackFor = Exception.class)
    public void register(User User) {
        //        this.addUser(user);
        try {
            this.addUser(User);
        } catch (DuplicateKeyException e) {
            // 解析数据库唯一约束名称
            String errorMsg = e.getCause().getMessage();
            if (errorMsg.contains("phone_unique")) { // 手机号唯一约束名
                throw new CustomeException("409", "phone:手机号已存在");
            }
            //            else if (errorMsg.contains("username_unique")) { // 用户名唯一约束名
            //                throw new CustomeException("409", "username:用户名已存在");
            //            }
        }
    }
}

